package com.icesoft.system.controller;

import com.icesoft.framework.core.binding.Binder;
import com.icesoft.framework.core.controller.BaseCrudRestController;
import com.icesoft.framework.core.exception.BusinessException;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.framework.core.vo.Pagination;
import com.icesoft.system.dto.UserDTO;
import com.icesoft.system.entity.*;
import com.icesoft.system.permission.OperationCons;
import com.icesoft.system.permission.annotation.BindPermission;
import com.icesoft.system.service.impl.*;
import com.icesoft.system.types.SystemSettingTypeDictionary;
import com.icesoft.system.types.UserTypeDictionary;
import com.icesoft.system.vo.RoleVO;
import com.icesoft.system.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 系统用户Controller
 *
 * @author ${author}
 * @date 230326
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@BindPermission(name = "系统用户管理")
@RequestMapping("/system/user")
public class UserController extends BaseCrudRestController<User> {

	private final AccountServiceImpl accountService;

	private final UserServiceImpl userService;

	private final UserRoleServiceImpl userRoleService;

	private final RoleServiceImpl roleService;

	private final SystemSettingTypeDictionary systemSettingTypeDictionary;

	private final UserTypeDictionary userTypeDictionary;

	private final OrgServiceImpl orgService;

	/**
	 * 查询ViewObject的分页数据
	 * <p>
	 * url请求参数示例: /list?field=abc&pageSize=20&pageIndex=1&orderBy=id
	 * </p>
	 *
	 * @return
	 * @throws Exception
	 */

	@GetMapping("/query")
	@BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
	public JsonResult getViewObjectListMapping(UserDTO entity, Pagination pagination) throws Exception {
		return super.getViewObjectList(entity, pagination, UserVO.class);
	}

	/**
	 * 根据资源id查询ViewObject
	 *
	 * @param id ID
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{id}")
	@BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
	public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
		return super.getViewObject(id, UserVO.class);
	}

	@GetMapping("/getUserDetail/{id}")
	@BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
	public JsonResult getUserDetail(@PathVariable("id") Long id) throws Exception {
		User user = userService.getEntityNoDataPermission(id);
		UserVO userVO = Binder.convertAndBindRelations(user, UserVO.class);
		Role role = roleService.getEntityNoDataPermission(userVO.getRoleId());
		userVO.setRole(Binder.convertAndBindRelations(role, RoleVO.class));
		return JsonResult.OK(userVO);
	}

	/**
	 * 新建
	 *
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/create")
	@BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
	public JsonResult createEntityMapping(@Valid @RequestBody UserDTO dto) throws Exception {
		Org org = orgService.getEntity(dto.getOrgId());
		dto.setCompanyId(org.getCompanyId());
		dto.setUserType(userTypeDictionary.system);
		Long accountCount = accountService.lambdaQuery().eq(Account::getUserType, userTypeDictionary.system).eq(Account::getAuthAccount, dto.getUsername()).count();
		Long userCount = userService.lambdaQuery().eq(User::getCode, dto.getUsername().toUpperCase()).count();
		if (accountCount > 0 || userCount > 0) {
			throw new BusinessException("账号【" + dto.getUsername() + "】重复");
		}
		if (dto.getRoleId() == null) {
			throw new BusinessException("请选择角色");
		}
		dto.setCode(dto.getUsername().toUpperCase());
		JsonResult<Map<String, Object>> entity = super.createEntity(dto);

		Map<String, Object> data = entity.getData();
		Long id = Long.parseLong(String.valueOf(data.get("id")));
		userRoleService.createEntity(new UserRole(id, dto.getRoleId()));
		accountService.createSystemEntity(dto, dto.getUsername());
		entity.setMsg("创建成功，密码：" + systemSettingTypeDictionary.getDefaultPassword());
		return entity;
	}

	@Override
	protected void afterCreated(User entityOrDto) throws Exception {
		super.afterCreated(entityOrDto);
	}

	/**
	 * 更新
	 *
	 * @param dto
	 * @return JsonResult
	 * @throws Exception
	 */
	@PostMapping("/update/{id}")
	@BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
	public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody UserDTO dto) throws Exception {
		User user = userService.getEntity(id);
		if (!user.getOrgId().equals(dto.getOrgId())) {
			Org org = orgService.getEntity(dto.getOrgId());
			dto.setCompanyId(org.getCompanyId());
		}
		return super.updateEntity(id, dto);
	}

	/**
	 * 根据id删除资源对象
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/delete/{id}")
	@BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
	public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
		if (accountService.lambdaQuery().eq(Account::getUserId, id).count() > 0) {
			accountService.remove(accountService.lambdaQuery().eq(Account::getUserId, id));
		}
		if (userRoleService.lambdaQuery().eq(UserRole::getUserId, id).count() > 0) {
			userRoleService.remove(userRoleService.lambdaQuery().eq(UserRole::getUserId, id));
		}
		JsonResult<?> jsonResult = super.deleteEntity(id);
		return jsonResult;
	}


}